import wx
import os
import re
import REgen
import atexit

def getClipboardContent():
    do = wx.TextDataObject()
    wx.TheClipboard.Open()
    success = wx.TheClipboard.GetData(do)
    wx.TheClipboard.Close()
    if success:
        return do.GetText()
    else:
        return ''



class MainWindow(wx.Frame):

    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,wx.ID_ANY, title)
        self.layout()

        self.Bind(wx.EVT_CLOSE, self.onClose)
        self.txtIn.Bind(wx.EVT_TEXT, self.onReChanged)
        self.reIn.Bind(wx.EVT_TEXT, self.onReChanged)
        self.reOut.Bind(wx.EVT_TEXT, self.onReChanged)
        self.fillFields()

        self.Show(1)

    def onReChanged(self, event):
        self.recalc()

    def onClose(self, event):
        self.copyOutput()
        self.Destroy()

    def layout(self):
        self.hSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.leftSizer = wx.BoxSizer(wx.VERTICAL)
        self.rightSizer = wx.BoxSizer(wx.VERTICAL)

        self.reIn = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
        self.reOut = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
        self.txtIn = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
        self.txtOut = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)

        self.SetSizer(self.hSizer)
        self.hSizer.Add(self.leftSizer, 1, wx.EXPAND)
        self.hSizer.Add(self.rightSizer, 1, wx.EXPAND)

        self.leftSizer.Add(self.reIn, 0, wx.EXPAND)
        self.leftSizer.Add(self.txtIn, 1, wx.EXPAND)
        self.rightSizer.Add(self.reOut, 0, wx.EXPAND)
        self.rightSizer.Add(self.txtOut, 1, wx.EXPAND)

        self.SetSize((600,400))


    def recalc(self):
        replaced = 'Incorrect regexp...'
        try:
            replaced = re.sub(self.reIn.GetValue(), self.reOut.GetValue(), self.txtIn.GetValue())
        except:
            pass
        self.txtOut.SetValue(replaced)

    def copyOutput(self):
        clipdata = wx.TextDataObject()
        clipdata.SetText(os.linesep.join(self.txtOut.GetValue().split('\n')))
        wx.TheClipboard.Open()
        wx.TheClipboard.SetData(clipdata)
        wx.TheClipboard.Close()
        wx.TheClipboard.Flush()


    def fillFields(self):
        self.txtIn.SetValue(getClipboardContent())
        lines = self.txtIn.GetValue().split('\n')
        globbed = REgen.generate(*lines)
        self.reIn.SetValue(globbed.as_re())
        self.reOut.SetValue(globbed.as_backref())
        self.recalc()


def main():
    app = wx.PySimpleApp()
    frame = MainWindow(None, -1, "Local refactoring tool")
    app.MainLoop()



if __name__ == "__main__":
    main()

